/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:43:19
 * @LastEditTime: 2025-06-05 17:43:22
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \golib\autoroute\controller\auth.go
 * hnxr
 */
package controller

import (
	"net/http"

	"gitee.com/haodreams/golib/minauth"
	"github.com/gin-gonic/gin"
)

// 认证回调函数, gin.H
var callbackNeedAuth func(*gin.Context) (any, error)

// SetNeedAuthCallback 设置认证回调函数, gin.H
func SetNeedAuthCallback(cb func(*gin.Context) (any, error)) {
	callbackNeedAuth = cb
}

func GetAuth() func(*gin.Context) (any, error) {
	return callbackNeedAuth
}

// AuthController 认证控制器
type AuthController struct {
	Controller
	Sess *minauth.Session
}

// Setup 初始化设置
func (m *AuthController) Setup(c *gin.Context, controllerName string) (err error) {
	err = m.Controller.Setup(c, controllerName)
	if err != nil {
		return
	}

	if callbackNeedAuth != nil {
		u, err := callbackNeedAuth(c)
		if err != nil {
			//返回一个错误就不继续了
			c.JSON(http.StatusUnauthorized, err.Error())
			return err
		}
		if user, ok := u.(*minauth.Session); ok {
			m.Sess = user
		}
	}
	return
}
